#!/bin/bash
# 
# Pre-commit hook that ensures the file git_version.cpp is updated to reflect
# the current version of the project as of this commit. This script parses the 
# output of git describe to get each component of the version number (assuming 
# the most recent tag follows the vX.Y.Z[rc] standard format), then generates 
# git_version.cpp in which the C++ constants are defined to have these values.
# The new version of git_version.cpp is then added to the commit.

# Meaning: v(number).(number)[.](optional number)[rc]-(number)-g(alphanumeric hash)
version_regex='v([0-9]+)\.([0-9]+)\.?([0-9]*)(rc)?-([0-9]+)-g([0-9|a-z]+)'
git_string=$(git describe --tags --long)

if [[ $git_string =~ $version_regex ]]; then
	major_version="${BASH_REMATCH[1]}"
	minor_version="${BASH_REMATCH[2]}"
	patch_version="${BASH_REMATCH[3]}"
	commits_ahead="${BASH_REMATCH[5]}"
else
	echo "Error: git describe did not output a valid version string. Unable to update git_version.cpp" >&2
	exit 1
fi

version_num="${major_version}.${minor_version}.${patch_version}"
version_num_plus_commits="${version_num}+${commits_ahead}"

# Working directory of a git hook is always the root of the repo
cat > $(pwd)/src/core/git_version.cpp <<EOM
/**
 * @file git_version.cpp
 *
 * This file is automatically created by the pre-commit hook that is distributed 
 * with Derecho in the githooks folder; this script should be installed in your 
 * local repository's .git/hooks/ directory.
 */

#include <derecho/core/git_version.hpp>

namespace derecho {

const int MAJOR_VERSION = $major_version;
const int MINOR_VERSION = $minor_version;
const int PATCH_VERSION = $patch_version;
const int COMMITS_AHEAD_OF_VERSION = $commits_ahead;
const char* VERSION_STRING = "${version_num}";
const char* VERSION_STRING_PLUS_COMMITS = "${version_num_plus_commits}";

}
EOM

git add $(pwd)/src/core/git_version.cpp
